const express = require('express');
const router = express.Router();
const { Setting } = require('../models');
const { success, failure } = require('../utils/responses');
const { NotFound } = require('http-errors');
const { setKey, getKey } = require('../utils/redis');

/**
 * 查询系统信息
 *
 * GET /categories
 * */

router.get('/', async function (req, res) {
  try {
    const cacheKey = 'setting';
    let setting = await getKey(cacheKey);

    if (!setting) {
      setting = await Setting.findOne();
      if (!setting) {
        throw new NotFound('未找到系统设置请联系管理员');
      }
      // 将数据写入缓存
      await setKey(cacheKey, setting);
    }

    success(res, '查询成功', { setting });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
